package pl.nazaweb.imedproplus.business.service;

import java.io.IOException;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import pl.nazaweb.imedproplus.business.service.util.XmlLoader;
import pl.nazaweb.imedproplus.model.entity.Icd9;
import pl.nazaweb.imedproplus.model.facade.Icd9Facade;

@LocalBean
@Stateless
public class Icd9Service extends XmlLoader {

    @EJB
    private Icd9Facade icd9Facade;

    public void loadIcd9DictionaryToDatabase(String fileName)
            throws ParserConfigurationException, SAXException, IOException {
        this.loadDocument(fileName);
        List<String> currentIcd9CodeList = this.icd9Facade.getIcd9CodeList();
        NodeList newIcd9 = this.getDocumentNodeList();
        for (int i = 1; i < newIcd9.getLength(); i++) {
            Element element = (Element) newIcd9.item(i);
            if (currentIcd9CodeList.contains(element.getAttribute("kod"))) {
                this.updateIcd(element);
            } else {
                this.addNewIcd9(element);
            }
        }

    }

    private void updateIcd(Element element) {
        this.icd9Facade.edit(this.getEntityFromElement(element));
    }

    private void addNewIcd9(Element element) {
        this.icd9Facade.create(this.getEntityFromElement(element));
    }

    private Icd9 getEntityFromElement(Element element) {
        Icd9 entity = new Icd9();
        entity.setCode(element.getAttribute("kod"));
        entity.setName(element.getAttribute("nazwa"));
        entity.setStatus(element.getAttribute("status").toUpperCase());
        return entity;
    }

    public List<Icd9> getIcd9List(int[] range) {
        return this.icd9Facade.findRange(range);
    }

    public List<Icd9> getIcd9List() {
        return this.icd9Facade.findAll();
    }
}
